<?php
namespace crontab\api;

class Action{

	static $socketAddr = 'http://127.0.0.1:8283';

	//添加任务
	public  static function add($data){
		$data['action'] = 'add';
		$res = self::request($data);
		$result = json_decode($res,true);
		if($result['code'] !== 200){
			throw new \Exception($result['msg']);
		}
		return true;
	}
	
	//删除任务
	public static  function delete($data){
		$data['action'] = 'delete';
		$res = self::request($data);
		$result = json_decode($res,true);
		if($result['code'] != 200){
			throw new \Exception($result['msg']);
		}
		return true;
	}


	//执行任务
	public  static  function run($data){
		$data['action'] = 'execute';
		$res = self::request($data);
		$result = json_decode($res,true);
		if($result['code'] != 200){
			throw new \Exception($result['msg']);
		}
		return true;
	}


	//暂停任务
	public  static  function suspend($data){
		$data['action'] = 'suspend';
		$res = self::request($data);
		$result = json_decode($res,true);
		if($result['code'] != 200){
			throw new \Exception($result['msg']);
		}
		return true;
	}

	//启动任务
	public  static  function start($data){
		$data['action'] = 'startUp';
		$res = self::request($data);
		$result = json_decode($res,true);
		if($result['code'] != 200){
			throw new \Exception($result['msg']);
		}
		return true;
	}

	public static  function  request($data){
		$url = self::$socketAddr;
		if(is_array($data)){
			$data = http_build_query($data);
		}
		$ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        $output = curl_exec($ch);
         if(curl_errno($ch)){
            throw new \Exception('curl 错误code:'.curl_errno($ch));
        }
        curl_close($ch);
        return $output;
	}
}